package thread.deadlock;

import java.util.List;

//死锁，多个线程互相等待，形成闭环死锁
public class DeadLock {
    public static void main(String[] args) {
        Makeup g1 = new Makeup(0,"x");
        Makeup g2 = new Makeup(1,"y");

        g1.start();
        g2.start();



    }
}

class Lipstick{

}

class Mirror{

}

class Makeup extends Thread{

    //需要的资源只有一份，用static 保证
    static Mirror mirror = new Mirror();
    static Lipstick lipstick = new Lipstick();

    int choice;//选择
    String name;

    public Makeup(int choice,String name){
        this.choice = choice;
        this.name = name;
    }

    @Override
    public void run() {
        //化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //互相持有对方的锁
    private void makeup() throws InterruptedException {
        if(choice == 0){
            synchronized (lipstick){ //获得口红的锁
                System.out.println(this.name + "获得口红锁");
                Thread.sleep(1000);
                synchronized (mirror){ //想获得镜子
                    System.out.println(this.name + "获得镜子锁");
                }
            }
        }else {
            synchronized (mirror){ //获得口红的锁
                System.out.println(this.name + "获得镜子锁");
                Thread.sleep(2000);
                synchronized (lipstick){ //想获得镜子
                    System.out.println(this.name + "获得口红锁");
                }
            }
        }


    }
}